<template>
  <div class="settlement-management">


    <div class="operation-buttons">
      <el-button type="info" class="mr-2" @click="handleImport">导入</el-button>
      <el-button type="info" class="mr-2" @click="handleExport">导出</el-button>
    </div>


    <!-- 筛选表单区域 -->
    <div class="filter-form">
      <el-form :inline="true" :model="filterForm" class="demo-form-inline">
        <!-- 结算状态筛选 -->
        <el-form-item label="结算状态">
          <el-select v-model="filterForm.settlementStatus" placeholder="请选择">
            <el-option label="全部" value=""></el-option>
            <el-option label="未结算" value="未结算"></el-option>
            <el-option label="已结算" value="已结算"></el-option>
            <el-option label="部分结算" value="部分结算"></el-option>
          </el-select>
        </el-form-item>

        <!-- 创建日期筛选 -->
        <el-form-item label="创建日期">
          <el-date-picker
            v-model="filterForm.createDateRange"
            type="daterange"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>

        <!-- 关键词搜索 -->
        <el-form-item>
          <el-input
            v-model="filterForm.keyword"
            placeholder="请输入关键词搜索"
            prefix-icon="el-icon-search"
            style="width: 200px"
          ></el-input>
        </el-form-item>

        <!-- 搜索和重置按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset" class="ml-2">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格区域 -->
    <div class="data-table">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        stripe
        v-loading="loading"
      >
        <!-- 复选框列 -->
        <el-table-column
          type="selection"
          width="55"
        ></el-table-column>

        <!-- 对账单号列 -->
        <el-table-column
          prop="statementNo"
          label="对账单号"
          width="120"
        ></el-table-column>

        <!-- 客户列 -->
        <el-table-column
          prop="customer"
          label="客户名称"
          width="150"
        ></el-table-column>

        <!-- 结算状态列 -->
        <el-table-column
          prop="settlementStatus"
          label="结算状态"
          width="100"
        >

          <template slot-scope="scope">
            {{ formatSettlementStatus(scope.row.settlementStatus) }}
          </template>
        </el-table-column>

        <!-- 订单总数量列 -->
        <el-table-column
          prop="totalOrders"
          label="订单总数量"
          width="100"
        ></el-table-column>

        <!-- 货物数量列 -->
        <el-table-column
          prop="goodsQuantity"
          label="货物数量"
          width="90"
        ></el-table-column>

        <!-- 货物总体积列 -->
        <el-table-column
          prop="totalVolume"
          label="货物总体积"
          width="100"
        ></el-table-column>

        <!-- 货物总重量列 -->
        <el-table-column
          prop="totalWeight"
          label="货物总重量"
          width="100"
        ></el-table-column>

        <!-- 应收总金额列 -->
        <el-table-column
          prop="receivableAmount"
          label="应收总金额(元)"
          width="120"
        ></el-table-column>

        <!-- 实收总金额列 -->
        <el-table-column
          prop="actualReceivedAmount"
          label="实收总金额(元)"
          width="120"
        ></el-table-column>

        <!-- 创建人列 -->
        <el-table-column
          prop="creator"
          label="创建人"
          width="90"
        ></el-table-column>

        <!-- 创建时间列 -->
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="160"
        ></el-table-column>

        <!-- 操作列 -->
        <el-table-column
          label="操作"
          width="80"
        >
          <template slot-scope="scope">
            <el-link type="primary" size="small">明细</el-link>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        v-show="total > 0"
        :current-page="queryParams.pageNum"
        :page-sizes="[5, 10, 20, 25]"
        :page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </div>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.action"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleFileError"
        :auto-upload="false"
        drag
        :file-list="upload.fileList"
        @change="handleFileChange"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStatement, exportStatement, importStatementTemplate ,importStatement} from "@/api/tms/recstatenote/state";
import { getToken } from "@/utils/auth";
import download from '@/plugins/download';  // 移除花括号，使用默认导入
export default {
  name: 'SettlementManagement',
  data() {
    return {
      // 筛选表单数据
      filterForm: {
        settlementStatus: '',
        createDateRange: [],
        keyword: ''
      },
      // 表格数据
      tableData: [],
      // 加载状态
      loading: false,
      // 分页参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 总记录数
      total: 0,


      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 上传的文件列表
        fileList: [],
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        action: process.env.VUE_APP_BASE_API + "/finance/settlement/importData"
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取列表数据
    getList() {
      this.loading = true;
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        keyword: this.filterForm.keyword,
        settlementStatus: this.filterForm.settlementStatus
      };

      // 处理日期范围
      if (this.filterForm.createDateRange && this.filterForm.createDateRange.length === 2) {
        params.beginCreateTime = this.filterForm.createDateRange[0];
        params.endCreateTime = this.filterForm.createDateRange[1];
      }

      console.log('列表查询参数:', params); // 调试信息

      listStatement(params)
        .then(response => {
          this.tableData = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch(error => {
          console.error('获取数据失败:', error);
          this.loading = false;
        });
    },

    // 搜索处理
    handleSearch() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 重置处理
    handleReset() {
      this.filterForm = {
        settlementStatus: '',
        createDateRange: [],
        keyword: ''
      };
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },


    // 格式化结算状态显示
    formatSettlementStatus(status) {
      // 确保status是字符串类型
      const statusStr = String(status).toLowerCase();

      const statusMap = {
        'unsettled': '未结算',
        'settled': '已结算',
        'partiallysettled': '部分结算', // 注意：这里可能是小写或大写混合
        'partialsettled': '部分结算',   // 可能的变体
        'partially_settled': '部分结算', // 下划线分隔的变体
        'partial_settled': '部分结算'    // 其他可能的拼写
      };

      // 返回映射后的值，如果找不到则返回原值
      return statusMap[statusStr] || status;
    },

    // 导入对话框相关方法
    handleImport() {
      this.upload.title = "导入对账单数据";
      this.upload.open = true;
    },

// 添加：处理文件变化事件，确保文件列表同步
    handleFileChange(file, fileList) {
      // 过滤掉格式错误的文件
      const validFiles = fileList.filter(f => {
        const ext = f.name.split('.').pop().toLowerCase();
        return ['xlsx', 'xls'].includes(ext);
      });

      // 强制同步文件列表（解决核心同步问题）
      this.upload.fileList = [...validFiles];

      // 显示格式错误提示
      if (fileList.length > validFiles.length) {
        this.$message.error("仅支持xls、xlsx格式文件，请重新选择");
      }
    },

    // 下载模板
    importTemplate() {
      this.loading = true;
      // 1. 定义导入模板所需的表头和示例数据
      const headers = [
        "对账单号",        // statementNo (必填)
        "承运商",          // carrier (必填)
        "结算状态",        // settlementStatus (必填：未结算/已结算)
        "订单总数量",      // totalOrders (必填)
        "应付总金额(元)",  // payableAmount (必填)
        "货物数量",        // goodsQuantity (可选)
        "货物总体积",      // totalVolume (可选)
        "货物总重量",      // totalWeight (可选)
        "实付总金额(元)",  // actualAmount (可选)
        "创建人"           // creator (可选)
      ];

      // 2. 创建CSV格式内容（Excel可直接打开CSV文件）
      const csvContent = [
        headers.join(','),  // 表头行
        'DZ20250906001,顺丰物流,未结算,50,12500.50,120,35.2,80.5,12300.00,admin',  // 示例数据行
        'DZ20250906002,圆通速递,已结算,30,8900.00,,,,8900.00,'  // 示例数据行（含可选空列）
      ].join('\n');

      // 3. 转换为Blob并下载
      try {
        const blob = new Blob(['\ufeff' + csvContent], {type: 'text/csv;charset=utf-8;'});
        download.saveAs(blob, "对账单导入模板.xlsx");  // 保存为xlsx扩展名（Excel兼容）
        this.loading = false;
        this.$message.success("模板下载成功");
      } catch (error) {
        this.loading = false;
        console.error("模板生成失败:", error);
        this.$message.error("模板下载失败，请重试");
      }

      importStatementTemplate({}).then(response => {
        this.loading = false;
        if (response instanceof Blob) {
          download.saveAs(response, "对账单导入模板.xlsx");  // 通过对象调用 saveAs
        } else if (response.data && response.data instanceof Blob) {
          download.saveAs(response.data, "对账单导入模板.xlsx");  // 通过对象调用 saveAs
        } else {
          this.$message.error("下载失败：无效的文件格式");
        }
      }).catch(error => {
        this.loading = false;
        console.error("下载模板失败:", error);
        this.$message.error("下载模板失败，请重试");
      });
    },


    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.upload.fileList = [];  // 清空文件列表
      this.$refs.upload.clearFiles();  // 清除上传组件的文件列表

      if (response.code === 200 || response.success) {
        this.$message.success("导入成功: " + (response.msg || "数据已成功导入"));
        this.getList(); // 刷新列表
      } else {
        this.$message.error("导入失败: " + (response.msg || "服务器处理失败"));
      }
    },

    // 文件上传失败处理
    handleFileError(error, file, fileList) {
      this.upload.isUploading = false;
      this.$message.error("上传失败: " + (error.message || "网络错误"));
    },

    // 提交文件表单
    submitFileForm() {
      // 直接获取上传组件的文件列表（绕过可能的同步问题）
      const uploadComponent = this.$refs.upload;
      if (!uploadComponent) {
        this.$message.error("上传组件加载失败");
        return;
      }

      // 直接从组件获取原始文件列表
      const fileList = uploadComponent.uploadFiles || [];

      // 调试日志（可保留用于问题排查）
      console.log("提交时的文件列表:", fileList.map(f => ({
        name: f.name,
        status: f.status,
        uid: f.uid
      })));

      // 检查是否有文件
      if (fileList.length === 0) {
        this.$message.warning("请选择要上传的文件");
        return;
      }

      // 检查文件状态（只接受可上传状态）
      const canUpload = fileList.some(f =>
        f.status === 'ready' ||  // 准备上传状态
        f.status === 'waiting'   // 等待上传状态
      );

      if (!canUpload) {
        this.$message.warning("没有可上传的文件，请重新选择");
        return;
      }

      // 直接调用上传组件的提交方法
      uploadComponent.submit();
    },


    // 导出按钮操作
    handleExport() {
      const params = {};
      if (this.filterForm.settlementStatus) params.settlementStatus = this.filterForm.settlementStatus;
      if (this.filterForm.keyword) params.keyword = this.filterForm.keyword;
      if (this.filterForm.createDateRange && this.filterForm.createDateRange.length === 2) {
        params.beginCreateTime = this.filterForm.createDateRange[0];
        params.endCreateTime = this.filterForm.createDateRange[1];
      }

      this.$confirm('是否确认导出数据?', "警告", {
        // ... 确认框配置保持不变 ...
      }).then(() => {
        this.loading = true;
        return exportStatement(params);
      }).then(response => {
        this.loading = false;
        if (response.type === 'text/html') {
          // 修复：通过对象调用 saveAs 方法（解决 "saveAs is not a function" 错误）
          download.saveAs(new Blob([response]), "对账单数据.xlsx");
        } else {
          // 修复：通过对象调用 saveAs 方法
          download.saveAs(response, "对账单数据.xlsx");
        }
      });
    }



  }
};
</script>

<style scoped>
.settlement-management {
  padding: 20px;
  background-color: #fff;
}

.operation-buttons {
  margin-bottom: 20px;
}

.filter-form {
  margin-bottom: 15px;
}

.data-table {
  margin-top: 10px;
}

.mr-2 {
  margin-right: 8px !important;
}

.ml-2 {
  margin-left: 8px !important;
}

.pagination {
  margin-top: 15px;
  text-align: right;
}

/* 导入弹窗样式 */
.el-upload__tip {
  margin-top: 10px;
}

.text-center {
  text-align: center;
}

.el-upload__tip span {
  display: block;
  margin-top: 5px;
  color: #999;
}
</style>

